package com.edu.glutdataconvertserver.util;

import com.google.common.base.Throwables;
import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;

import java.io.UnsupportedEncodingException;

public class HashUtils {


    private static final HashFunction FUNCTION = Hashing.md5();

    private static final HashFunction MURMUR_FUNC = Hashing.murmur3_128();

    private static final String SALT = "caitangyun";

    public static String encryPassword(String password) {
        String plain = Encodes.unescapeHtml(password);
        byte[] salt = Digests.generateSalt(8);
        byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, 1024);
        return Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword);
    /*HashCode code = FUNCTION.hashString(password+SALT, Charset.forName("UTF-8"));
    return code.toString();*/
    }

    public static boolean validatePassword(String plainPassword, String password) {
        String plain = Encodes.unescapeHtml(plainPassword);
        byte[] salt = Encodes.decodeHex(password.substring(0, 16));
        byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, 1024);
        return password.equals(Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
    }

    public static String hashString(String input) {
        HashCode code = null;
        try {
            code = MURMUR_FUNC.hashBytes(input.getBytes("utf-8"));
        } catch (UnsupportedEncodingException e) {
            Throwables.propagate(e);
        }
        return code.toString();
    }

    public static void main(String[] args) {
        System.out.println(encryPassword("123456"));
        System.out.println(validatePassword("123456", "4e5531ba6cf49e90db37b0f337baee428b92c38b3646e41852a2280a"));
        System.out.println(validatePassword("123456", "863d9afe7a10bd54e1bd1afc0b3dba41179c621b26a28a9f4eee3f54"));
    }
}
